package xyz.xiangyushui.controller.membership.active;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.dao.user.member.MembershipDao;
import xyz.xiangyushui.dao.user.member.MembershipProfileDao;
import xyz.xiangyushui.dao.user.member.RenewalHistoryDao;

/**
 * Servlet implementation class ActivePost
 */
@WebServlet("/activePost")
public class ActivePost extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String invalidInput="invalid input";
	private MembershipDao md;
	private MembershipProfileDao mpd;
	private RenewalHistoryDao rhd;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActivePost() {
        super();
        md=new MembershipDao();
        mpd=new MembershipProfileDao();
        rhd=new RenewalHistoryDao();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String money=request.getParameter("money");
		String bankCard=request.getParameter("bankCard");
		String msg=validate(bankCard, money);
		if(msg.equals("success")){
			String userName=(String) request.getSession(false).getAttribute("userName");
			md.changeBalance(userName, Double.parseDouble(money));
			rhd.addRenewalRecord(userName, Double.parseDouble(money));
			mpd.updateBankCard(userName, bankCard);
			md.updateStateOK(userName);
			request.getRequestDispatcher("/router").forward(request, response);
		}else{
			request.setAttribute("failedMsg", msg);
			request.getRequestDispatcher("/active").forward(request, response);
		}
		
	}
	
	private String validate(String bankCard,String money){
		if("".equals(bankCard)||"".equals(money)){
			return invalidInput;
		}else{
			try{
				double d=Double.parseDouble(money);
				if(d<200.0){
					return invalidInput;
				}
			}catch(NumberFormatException e){
				return invalidInput;
			}
		}
		return "success";
	}

}
